package com.elasticjob.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.elasticjob.domian.FileCustom;
import com.elasticjob.mapper.FileCustomMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 找个比较大的车，把东西都搬过去
 */
@Component
public class FileCustomElasticJob implements SimpleJob {
    @Autowired
    private FileCustomMapper fileCustomMapper;


    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println("分片参数为:" + shardingContext.getShardingParameter());
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String type) {
        //1 把数据库中标 backedUp=0 的数据查询出来
//        List<FileCustom> fileCustoms = fileCustomMapper.selectBackedUpEqualZero();
        List<FileCustom> fileCustoms = fileCustomMapper.selecByType(type);
        System.out.println("需要备份文件个数:" + fileCustoms.size());

        //2 遍历 模拟备份(睡1s) 然后修改状态
        for (FileCustom fileCustom : fileCustoms) {
            backUpFile(fileCustom);
        }
    }

    private void backUpFile(FileCustom fileCustom) {
        System.out.println("要备份数据的id为:====>" + fileCustom.getId()
                + "要备份数据的类型为:====>" + fileCustom.getType());
        try {
            //模拟备份动作
            TimeUnit.SECONDS.sleep(1);
            //Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行文件备份====>" + fileCustom);
        fileCustomMapper.changeState(fileCustom.getId(), 1);
    }
}